<template>
  <div>
    <NDropdown :options="menus" @select="handleMenuClick">
      <NAvatar round v-if="islogin" :src="userlogo"></NAvatar>
      <NAvatar round v-else src="/user.svg"></NAvatar>
    </NDropdown>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { NDropdown, NAvatar } from 'naive-ui'
import { useUserStore } from '@/stores/useStore'
import { storeToRefs } from 'pinia'

import { useRouter } from 'vue-router'
const router = useRouter()
import { Api } from '@/types/Api'

const { updateUserInfo } = useUserStore()
const { islogin, user, userlogo } = storeToRefs(useUserStore())

const logout = () => {
  Api.delete('/auth', {}, () => {
    updateUserInfo(() => {
      router.push('/user/login')
    })
  })
}

const menus = ref([
  {
    label: '首页',
    key: 'home',
  },
  {
    label: '登录',
    key: 'login',
  },
  {
    label: '注册',
    key: 'reg',
  },
])

//watch是监听值变化，参数1是要监听的值
//参数2是值变化后要执行的函数
watch(islogin, () => {
  watchLogin()
})

const watchLogin = () => {
  if (islogin.value) {
    menus.value = [
      {
        label: '首页',
        key: 'home',
      },
      {
        label: user.value.username,
        key: 'userinfo',
      },
      {
        label: '安全退出',
        key: 'logout',
      },
    ]
  }
}

const handleMenuClick = (key: string) => {
  if (key === 'logout') {
    logout()
  } else if (key === 'home') {
    router.push('/')
  } else if (key === 'login') {
    router.push('/user/login')
  }
}

onMounted(() => {
  watchLogin()
})
</script>

<style scoped></style>
